package com.hqd.jjvm.classformat.attributeinfo;

import com.hqd.jjvm.classformat.AttributeType;
import com.hqd.jjvm.classformat.ClassFile;

/**
 * 属性工厂
 *
 * @author hqd
 */
public class AttributeInfoFactory {
    private static final String BASE_PACKAGE = "com.hqd.jjvm.classformat.attributeinfo.";

    private static Class<? extends AttributeInfo> getClassType(AttributeType attributeType) throws ClassNotFoundException {
        Class<? extends AttributeInfo> clazz = null;
        try {
            clazz = (Class<? extends AttributeInfo>) Class.forName((BASE_PACKAGE + attributeType.getCode()).intern());
        } catch (ClassNotFoundException e) {
            clazz = (Class<? extends AttributeInfo>) Class.forName((BASE_PACKAGE + attributeType.getCode() + "Attribute").intern());
        }
        return clazz;
    }

    public static AttributeInfo newAttributeInfo(ClassFile classFile, AttributeType attributeType) {
        try {
            Class<? extends AttributeInfo> clazz = getClassType(attributeType);
            // 获取带参构造方法对象
            // public Constructor<T> getConstructor(Class<?>... parameterTypes)
            AttributeInfo attributeInfo = clazz.newInstance();
            attributeInfo.newAttributeInfo(classFile);
            return attributeInfo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
